/*
	Copyright (c) 2008, Grant Jones <grant@podtronics.com>.
	All rights reserved.

	Redistribution and use in source and binary forms, with or
	without modification, are permitted provided that the following
	conditions are met:

		Redistributions of source code must retain the above copyright
		notice, this list of conditions and the following disclaimer.
		
		Redistributions in binary form must reproduce the above copyright
		notice, this list of conditions and the following disclaimer in
		the documentation and/or other materials provided with the
		distribution.
		
		Neither the name of the gxjones.com nor the names of its
		contributors may be used to endorse or promote products derived
		from this software without specific prior written permission.
	
	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
	"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
	LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
	FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
	COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
	INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
	(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
	SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
	HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
	STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
	ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
	OF THE POSSIBILITY OF SUCH DAMAGE.
	
	http://www.opensource.org/licenses/bsd-license.php
*/

/*
 *  edb_msg_utils.c
 *  scatterd
 *
 *  Created by Grant Jones on 2/25/08.
 *
 */

#include "edb_main.h"
#include "edb_msg_parser.h"
#include "edb_msg_utils.h"



char *edb_strdup( mempool_t *pool, const char *s1, int s1_len, const char *debug_name )
{
	char *r = mempool_malloc_named( pool, s1_len+1, (debug_name==NULL?"edb_strdup":debug_name) );
	
	if(!r)
		return NULL;
	
	memcpy( r, s1, s1_len );
	r[s1_len] = '\0';
	
	return r;
}


int edb_malloc_result_attr( mempool_t *pool, edb_net_item_attr_t *attr, const char *key, size_t key_sz, size_t value_sz )
{
//	size_t key_sz = strlen(key);
	attr->key = mempool_malloc_named(pool, key_sz+1, "attribute key" );
	attr->value = mempool_malloc_named(pool, value_sz+1, "attribute value" );
	if(!attr->key || !attr->value)
		return -1;
	memcpy( attr->key, key, key_sz );
	attr->key[key_sz] = '\0';

	attr->value_sz = value_sz;

	return 0;
}


int edb_term_result_attr( mempool_t *pool, edb_net_item_attr_t *attr, const char *key, const char *value_fmt, ... )
{
	va_list ap;
	int req_len = 0;
	va_start(ap, value_fmt);
	req_len = vsnprintf(NULL, 0, value_fmt, ap);
	va_end(ap);
	
	if( edb_malloc_result_attr( pool, attr, key, strlen(key), req_len ) )
		return -1;
	
	/* req_len+1 because vsnprintf will want to put a NULL-term at the end,
	** edb_malloc_result_attr allocates value_sz+1 for just this reason. */
	
	va_start(ap, value_fmt);
	vsnprintf(attr->value, req_len+1, value_fmt, ap);
	va_end(ap);
	
	return 0;
}



edb_net_item_t *edb_add_result( cmapStruct *result_items, size_t attr_count )
{
	edb_net_item_t *t = (edb_net_item_t *)mempool_malloc_named(result_items->mempool, sizeof(edb_net_item_t)+(sizeof(edb_net_item_attr_t)*attr_count), "edb_add_result" );
	cmap_assign(result_items, cmap_gethighestkey(result_items)+1, t );
	
	t->attrs = (edb_net_item_attr_t *) &((char *)t)[sizeof(edb_net_item_t)];
	t->attr_count = attr_count;
	
	return t;
}

/* **************************************************************************
value token utils:
************************************************************************** */


void edbDestroyToken( Token *t )
{
	printf("edbDestroyToken\n");
}

Token *edbValueFromID( edbParseContext *ctx, Token *t )
{
	Token *r = mempool_malloc_named(ctx->out_items->mempool, sizeof(Token)+t->n, __FUNCTION__ );
	r->z = &((unsigned char *)r)[sizeof(Token)];
	r->n = t->n;
	
	memcpy( (unsigned char *)r->z, t->z, r->n );
	return r;
}
Token *edbDequote( edbParseContext *ctx, Token *t )
{
	// removes quotes from a token (the token is assumed to be of type: TK_STRING)
	// Nearly identical to the SQLite version however, it does not assume that the
	// token is NULL terminated -- because it isn't.
		
	Token *r = edbValueFromID(ctx, t);

	int quote;
	int i, j, k;
	char *z;
	if( r->n == 0 ) return r;
	z = (char *)r->z;
	quote = z[0];
	switch( quote )
	{
	case '\'':  break;
	case '"':   break;
	case '`':   break;                /* For MySQL compatibility */
	case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
	default:    return r;
	}
	
	for(i=1, j=0, k = r->n; k; i++, k--)
	{
		if( z[i]==quote )
		{
			if( i == r->n-1 || z[i+1]!=quote )	/* z[i+1] may go beyond allocated buffer, i==r->n-1 will catch this case */
				break;

			z[j++] = quote;
			i++;
		}
		else
		{
			z[j++] = z[i];
		}
	}
	
	// j is the new string length:
	r->n = j;

	return r;
}

Token *edbResolveVariable( edbParseContext *ctx, Token *var_name )
{
	size_t i;
	mempool_t *pool = ctx->out_items->mempool;
	
	Token *var_value = mempool_malloc_named(pool, sizeof(Token), __FUNCTION__ );	
	var_value->n = 0;
	var_value->z = (unsigned char *)"";
	
	if( ctx->current_in_item >= ctx->in_item_count )
		goto finished;
	
	edb_net_item_t *citem = &ctx->in_items[ctx->current_in_item];
	
	for( i = 0; i < citem->attr_count; i ++ )
	{
		char *key = citem->attrs[i].key;
		int key_len = strlen(key);
		
		// case sensitive compare for now:
		if( key_len == var_name->n-1 &&
			memcmp(&var_name->z[1], key, key_len) == 0 )
		{
			var_value->n = citem->attrs[i].value_sz;
			var_value->z = citem->attrs[i].value;
			goto finished;
		}
	}
	
finished:
/*
	edb_log_printf(0,"variable named: ");
	edb_log_dump(0, var_name->z, var_name->n );
	edb_log_printf(0,"\nresolved variable value: ");
	edb_log_dump(0,var_value->z, var_value->n );
	edb_log_printf(0,"\n");
*/	
	return var_value;	
}



/* **************************************************************************
AttrValue - Attribute Value functions
************************************************************************** */
AttrValue *edbCreateAttrValueFromPool( mempool_t *pool, Token *key, Token *value )
{
/*	int key_len = key->n;*/
	int value_len = (value==0?0:value->n);
//	printf("edbCreateAttrValue\n");	
	
	if(!key)
		return NULL;
	
	AttrValue *v = mempool_malloc_named(pool, sizeof(AttrValue)+key->n+value_len, __FUNCTION__ );
	v->key.n = key->n;
//	v->key.dyn = 0;
	v->key.z = &((unsigned char *)v)[sizeof(AttrValue)];
	memcpy( (void *)v->key.z, key->z, key->n );
	if( value )
	{
		v->value.n = value_len;
//		v->value.dyn = 0;
		v->value.z = &((unsigned char *)v)[sizeof(AttrValue)+key->n];
		memcpy( (void *)v->value.z, value->z, value_len );
	}
	else
	{
		v->value.n = 0;
		v->value.z = NULL;
	}
	return v;
}
/*         0        1         2         3   */
/*         12345678901234567890123456789012 */
AttrValue *edbCreateAttrValueCStrFromPool( mempool_t *pool, const char *key, Token *value )
{
	Token key_token;
	key_token.z = (unsigned char *)key;
	key_token.n = strlen(key);
	return edbCreateAttrValueFromPool( pool, &key_token, value );
}

AttrValue *edbCreateAttrValueCStr( edbParseContext *ctx, const char *key, Token *value )
{
	return edbCreateAttrValueCStrFromPool( ctx->out_items->mempool, key, value );
}


AttrValue *edbCreateAttrValue( edbParseContext *ctx, Token *key, Token *value )
{
	return edbCreateAttrValueFromPool( ctx->out_items->mempool, key, value );
}

AttrValue *edbCreateAttrValueFromInteger( edbParseContext *ctx, Token *key, Token *int_value )
{
	// TODO
	return edbCreateAttrValue( ctx, key, int_value );	
}

void edbDestroyAttrValue( AttrValue *v )
{
/*	printf("edbDestroyAttrValue : 0x%.8x\n", (unsigned int)v );*/

}



/* **************************************************************************
AttrList - Attribute List functions
************************************************************************** */
AttrList *edbAppendAttrListFromPool( mempool_t *pool, AttrList *l, AttrValue *a )
{
	/* AttrList is actually a cmap in this implementation, it is allocated
	 * off the out_items cmap's mempool.
	 */
	AttrList *list = (l==0?cmap_new(pool):l);

//	printf("edbAppendAttrList : l = 0x%.8x, a = 0x%.8x\n", l, a );

	/* key ends up being allocated twice, meh: */
	strmap_assign(list, (const char *)a->key.z, a->key.n, a );
	
//	cmap_assign(list, list->num, a);
	
	return list;
}

AttrList *edbAppendAttrList( edbParseContext *ctx, AttrList *l, AttrValue *a )
{
	return edbAppendAttrListFromPool(ctx->out_items->mempool, l, a );
}

void edbAttrListDestroy( AttrList *l )
{
//	printf("edbAttrListDestroy : 0x%.8x\n", l );
	if(!l)
		return;
	cmap_destroy(l);
}






